package main

import (
	"Study_go/LogAgent/conf"
	"Study_go/LogAgent/etcd"
	"Study_go/LogAgent/kafka"
	"Study_go/LogAgent/taillog"
	"Study_go/LogAgent/utils"
	_"context"
	"fmt"
	"gopkg.in/ini.v1"
	"sync"
	"time"
)

var (
	cfg =new(conf.LogAgent)
)
func main(){
	//1 加载配置文件
	err:=ini.MapTo(cfg,"./conf/config.ini")
	if err!=nil{
		fmt.Println("加载配置文件失败")
		return
	}
	//2 初始化kafka
	err = kafka.Init([]string{cfg.Kafka.Address},cfg.Kafka.MaxSize)
	if err!=nil{
		fmt.Println("kafka连接失败")
		return
	}
	fmt.Println("kafka连接成功")

	//3 初始化etcd
	err = etcd.Init(cfg.Etcd.Address,time.Duration(cfg.Etcd.Timeout)*time.Second)
	if err!=nil{
		fmt.Println("etcd 连接失败")
		return
	}
	fmt.Println("etcd成功")
	//3.1 从etcd中拉取配置项
	//获取ip
	ipstr,err:=utils.GetOutboundIP()
	if err!=nil{
		panic(err)
	}
	etcdConfCollect:=fmt.Sprintf(cfg.Etcd.CollectLogConf,ipstr)
	logEntryConf,err:=etcd.GetConf(etcdConfCollect)
	if err!=nil{
		fmt.Println("从etcd中拉取数据失败",err)
		return
	}
	fmt.Println("从etcd中拉取数据成功：")
	for i,v:=range logEntryConf{
		fmt.Printf("index:%v value:%v\n",i,v)
	}
	//3.2 将etcd中拉取到的数据，通过tail打开path，然后写入到kafka
	taillog.Init(logEntryConf)
	//3.3 派一个watch监听日志收集项的变化
	newconfch:=taillog.ExportlogEntryChan()
	var wg sync.WaitGroup
	wg.Add(1)
	go etcd.WatchConf(cfg.Etcd.CollectLogConf,newconfch)
	wg.Wait()
	//3 初始化taillog
	//err = taillog.Init(cfg.Taillog.Filename)
	//if err!=nil{
	//	fmt.Println("读取日志初始化失败")
	//	return
	//}
	//fmt.Println("读取日志初始化成功")
	//4 具体业务，目前是从tail中读取日志，然后存放到kafka
	//run()
}

func run(){
	//从tail中读取数据
	//for{
	//	select{
	//		//存到kafaka中
	//		case line:=<-taillog.ReadData():
	//			kafka.SendMsg(cfg.Kafka.Topic,line.Text)
	//		default:
	//			time.Sleep(time.Second)
	//	}
	//}
}
